/* 
 * File:   FileWriter.cpp
 * Author: Guilherme Monteiro
 * 
 */

#include "../headers/FileWriter.h"


FileWriter::FileWriter(string outputFilePath) {
    this->outputFilePath = outputFilePath;
}

FileWriter::FileWriter(const FileWriter& orig) {
}

FileWriter::~FileWriter() {
}

/**
 * Write the header of first table in page.
 * 
 * @param leftUpper
 * @param rightBottom
 */
void FileWriter::writeHeader1(CvPoint leftUpper, CvPoint rightBottom) {
    File* file = new File(this->outputFilePath.c_str());
    char buffer[50];
    sprintf(buffer, "#%d,%d,%d,%d", leftUpper.x, leftUpper.y,
            rightBottom.x, rightBottom.y);
    file->writeHeader1(buffer);
    
//    printf("buffer1: %s\n", buffer);
}

/**
 * Write the header of one table that is not
 * the first table in page.
 * 
 * @param leftUpper
 * @param rightBottom
 */
void FileWriter::writeHeaderN(CvPoint leftUpper, CvPoint rightBottom) {
    File* file = new File(this->outputFilePath.c_str());
    char buffer[50];
    sprintf(buffer, "#%d,%d,%d,%d", leftUpper.x, leftUpper.y,
            rightBottom.x, rightBottom.y);
    file->writeHeaderN(buffer);
    
//    printf("bufferN: %s\n", buffer);
}

/**
 * Add left upper and right bottom of roi
 * in the end of vector of cells transcribed, adapt
 * it and, finally, writes the points in output file,
 * identified in metainfo.
 * 
 * @param leftUpper: leftupper point in low resolution
 * @param rightBottom: rightbottom point in low resolution
 * @param cellsTranscribedAndAdapted: vector of cells in low resolution
 */
void FileWriter::writeCells(vector<Cell> cellsTranscribedAndAdapted) {
    File* fileToApp = new File(this->outputFilePath);
    fileToApp->open();
    
    //printf("pointsAdapted.size(): %d \n", pointsAdapted.size());
    
    vector<Cell> cellsInFile;
    vector<Cell>::iterator itCells;
    for(itCells = cellsTranscribedAndAdapted.begin(); itCells != cellsTranscribedAndAdapted.end(); itCells++) {
        if(!contains(cellsInFile, *(itCells))) {
        
            char buffer[50];
//            printf("line : (%d,%d) - (%d,%d)\n", currentPoint.x, currentPoint.y, nextPoint.x, nextPoint.y);

            sprintf(buffer, "%d,%d,%d,%d", (*itCells).leftUpper.x, 
                    (*itCells).leftUpper.y,
                    (*itCells).rightBottom.x, 
                    (*itCells).rightBottom.y);

            fileToApp->writeLine(buffer);
            
            cellsInFile.push_back(*itCells);
        }
    }
    fileToApp->close();
}

/**
 * Verify if the vector of cells
 * contains the specific cell.
 * 
 * @param vCells
 * @param cell
 * @return true if contains
 */
bool FileWriter::contains(vector<Cell> vCells, Cell cell) {
    vector<Cell>::iterator it;
    for(it = vCells.begin(); it != vCells.end(); it++) {
        if(cell.equals(*it)) {
            return true;
        }
    }
    return false;
}